package it.duecaffe.claysoftware.ejb;

import it.duecaffe.claysoftware.exception.LoginException;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.naming.InitialContext;
import javax.naming.NamingException;

@Stateless
@LocalBean
public class LoginEjb implements LoginEjbLocal {
	
	Connection connection = null;
	
	public LoginEjb() {
		InitialContext initialContext;
		try {
			initialContext = new InitialContext();
			javax.sql.DataSource ds = (javax.sql.DataSource) initialContext.lookup("jdbc/clayAssMysql");
			connection = ds.getConnection();
		} catch (NamingException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void login(String username, String password) throws LoginException {
		String sql = "SELECT UT_CODICE, UT_NOME FROM TB_UTENTI WHERE UT_CODICE=?";
		try {
			PreparedStatement ps = connection.prepareStatement(sql);
			ps.setString(1, username);
			ResultSet rs = ps.executeQuery();
			if (!rs.next()) {
				throw new LoginException(username, password, "Utente non trovato");
			}
		} catch (SQLException e) {
			throw new LoginException(username, password, e.getMessage());
		}
	}
}
